const app = getApp();
const { appJson = [], module = '' } = app.siteInfo;
const { qyWXCheckSeesion } = require('../../../common/utils/ws/ws-wxwork');

Component({
  properties: {
    categoryid: {
      type: String,
      optionalTypes: [Number],
      value: ''
    },
    themeColors: {
      type: String,
      value: ''
    }
  },
  data: {
    curr: '',
    curr2: '',
    level2: '',
    typelist: [],
    typesublist: [],
    showsubtype: false,
    p: 2,
    height: '',
    heightTop: '',
    _switch: false,
    abnorData: {
      imgSrc: '/common/static/images/abnor-04.png',
      text: '暂无相关海报',
    },
    checked: true,
    showdisclaimer: false,
    showFloatButton: false,
    isTabShow: true, // 二级页是否全部展示
    toView: '',
    isWXWork: app.isWXWork,
  },

  created: function() {
    let shopid = (app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.shopid) || '';
    let openid = wx.getStorageSync('OPENID') || wx.getStorageSync('openid');
    this.setData({
      openid,
      shopid,
    });
    
  },
  attached() {
    // this.getPosterType();
    // this.getPosterLists(this.data.curr);
    // this.setData({
    //   height: wx.getSystemInfoSync().windowHeight,
    // });
  },
  ready() {
    // 这里兼容两种情况：1.直接跳转本页面 2.在页面中引用组件
    const curr = (this.options && this.options.categoryid) || (this.data && this.data.categoryid) || '';
    let animation = wx.createAnimation({
      duration: 500,
      timingFunction: 'ease',
    });
    this.animation = animation;

    module && module !== 'ws_empty' && this.setData({
      showFloatButton: true,
    });
    
    if (this.data.isWXWork){
      qyWXCheckSeesion({
        success: (res) => {
          console.log('企业微信登录成功', res);
          this.setData({
            height: wx.getSystemInfoSync().windowHeight,
            curr
          },() => {
            this.getPosterType();
            this.getPosterLists(curr);
          });
        },
        fail: (err) => {
          console.log('企业微信登录失败', err);
        },
      });
    } else {
      this.getPosterType();
      this.getPosterLists(curr);
    }
    
    this.setData({
      height: wx.getSystemInfoSync().windowHeight,
      curr
    },() => {
      this.getPosterType();
      this.getPosterLists(curr);
    });
  },
  methods: {
    previewModel(e) {
      let src = e.currentTarget.dataset.src;
      let srcs = [];
      srcs.push(src);
      wx.previewImage({
        current: src,
        urls: srcs,
      });
    },
    showAllTab() {
      this.setData({
        isTabShow: false,
      });
    },
    hideAllTab() {
      this.setData({
        isTabShow: true,
      });
    },
    showEdit(e) {
      let {
        tmpid,
        type,
        index,
      } = e.currentTarget.dataset;
      wx.setStorageSync('posterDetail', this.data.list[index]);
      app.util.navigateTo('/common/page/editPoster/index', {
        type,
        tmpid,
      });
    },
    showDisclaimer(e) {
      this.setData({
        dataset: e,
        checked: true,
      }, function() {
        if (wx.getStorageSync('agreeDisclaimer')) {
          this.showEdit(e);
        } else {
          this.setData({
            showdisclaimer: true,
          });
        }
      });
    },
    loadmore() {
      let that = this;
      let oldlist = that.data.list;
      let page = that.data.p;
      wx.showLoading({
        title: '加载中...',
        mask: true,
      });
      app.util.request({
        url: 'wxapp/poster/getPosterLists',
        data: {
          page: page,
          categoryid: that.data.curr,
          categorysubid: that.data.curr2,
          openid: that.data.openid,
          corpid: wx.getStorageSync('qyUserInfo').corpid
        },
        method: 'POST',
        success: function(res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            let list = res.data.result;
            let newlist = [];
            if (list.length > 0) {
              newlist = oldlist.concat(list);
              page += 1;
            } else {
              newlist = oldlist;
              wx.showToast({
                title: '没有更多数据了',
                icon: 'none',
              });
            }
            that.setData({
              list: newlist,
              p: page,
            });
          }
        },
        complete: function() {},
      });
    },
    switchType(e) {
      let that = this;
      let id = Number(e.currentTarget.dataset.typeid);
      let mainid = that.data.curr;
      let typelist = that.data.typelist;
      let subid = that.data.curr2;
      if (!subid) {
        subid = '';
      }
      this.setData({
        isTabShow: true,
      });
      if (Number(mainid) !== Number(id)) {
        that.setData({
          curr: id,
          curr2: '',
          p: 2,
          _switch: true,
          list: [],
          toView: '',
        });
        that.getPosterLists(id);
      }
      if (id) {
        for (let i in typelist) {
          if (Number(typelist[i].id) === id) {
            let children_list = typelist[i].children_list || [];
            that.setData({
              typesublist: children_list,
            });
            if (children_list.length > 0) {
              that.setData({
                showsubtype: true,
              });
            } else {
              that.setData({
                showsubtype: false,
              });
            }
            break;
          }
        }
      } else {
        that.setData({
          typesublist: [],
          showsubtype: false,
        });
      }
    },
    chooseCateType(e) {
      let subid = Number(e.currentTarget.dataset.typetwoid);
      this.getPosterLists(this.data.curr, subid);
      this.setData({
        showsubtype: false,
        curr2: subid,
        _switch: true,
        list: [],
        isTabShow: true,
        p: 2,
      });
      if (!this.data.isTabShow) {
        this.setData({
          isTabShow: true,
        });
      }
      let target = e.currentTarget.dataset.opt;
      this.setData({
        toView: target,
      });
    },
    closeCateModel() {
      this.setData({
        showsubtype: false,
      });
    },
    getPosterLists(id, subid = '') {
      let that = this;
      wx.showLoading({
        title: '加载中...',
      });
      console.log("====corpid===", wx.getStorageSync('qyUserInfo').corpid)
      app.util.request({
        url: 'wxapp/poster/getPosterLists',
        data: {
          page: 1,
          categoryid: id,
          categorysubid: subid,
          openid: that.data.openid,
          corpid: wx.getStorageSync('qyUserInfo').corpid
        },
        method: 'POST',
        success: function(res) {
          wx.hideLoading();
          if (res.statusCode === 200) {
            if (res.data.result) {
              that.setData({
                list: res.data.result,
              });
            }
          }
        },
      });
    },
    getPosterType() {
      let that = this;
      app.util.request({
        url: 'wxapp/poster/getCategorys',
        data: { corpid: wx.getStorageSync('qyUserInfo').corpid},
        method: 'POST',
        success: function(res) {
          if (res.statusCode === 200) {
            const typelist = res.data.result;
            that.setData({
              typelist,
            },() => {
              that.getTypeSubList();
            });
          }
        },
      });
    },
    loadModelList(e) {
      let that = this;
      let id = Number(e.currentTarget.dataset.typeid);
      that.setData({
        curr: id,
        list: [],
        p: 2,
      });
      app.util.request({
        url: 'wxapp/poster/moduleList',
        data: { corpid: wx.getStorageSync('qyUserInfo').corpid},
        success: (res) => {
          if (res.statusCode === 200) {
            if (res.data.result && res.data.result.length > 0) {
              that.setData({
                list: res.data.result,
                typesublist: [],
              });
            } else {
              that.setData({
                typesublist: []
              });
            }
          }
        },
      });
    },
    toAddPoster(e) {
      app.util.navigateTo('common/page/addPoster/index', {
        mid: e.currentTarget.dataset.tmpid,
      });
    },
    deletePoster(e) {
      let that = this;
      let {
        openid,
        id,
      } = e.currentTarget.dataset;
      let list = that.data.list;
      wx.showModal({
        title: '提示',
        content: '确定要删除该海报模板吗？',
        success: (res) => {
          if (res.confirm) {
            app.util.request({
              url: 'wxapp/poster/delModule',
              data: {
                page_id: id,
                openid,
                corpid: wx.getStorageSync('qyUserInfo').corpid
              },
              success: (res) => {
                if (res.statusCode === 200) {
                  for (let i in list) {
                    if (Number(list[i].id) === Number(id)) {
                      list.splice(i, 1);
                      that.setData({
                        list,
                      });
                      wx.showToast({
                        title: '删除成功',
                        icon: 'success',
                      });
                      break;
                    }
                  }
                } else {
                  wx.showToast({
                    title: '删除失败',
                    icon: 'icon',
                  });
                }
              },
            });
          }
        },
      });
    },
    changeradio(e) {
      this.setData({
        checked: !this.data.checked,
      });
    },
    closedisclaimer() {
      this.setData({
        showdisclaimer: false,
      });
    },
    confirm() {
      wx.setStorageSync('agreeDisclaimer', true);
      this.closedisclaimer();
      this.showEdit(this.data.dataset);
    },
    toHome() {
      const isCompanyCloudTemplate = Number(app.siteInfo.isCloudTemplate) === 1;
      if (isCompanyCloudTemplate) {  // 企业云端发布
        app.util.navigateTo('ws_micro_company_collection/pages/index/index', '', true);
        return;
      }
      let appJson = app.siteInfo.appJson[app.tabbarindex || 0];
      const url = appJson.homePage || (appJson.tabBar && appJson.tabBar.list && appJson.tabBar.list[0].pagePath);
      app.util.navigateTo(url, {}, 'all');
    },
    getTypeSubList() {
      const { curr: id ='', typelist = [] } = this.data;
      if (id) {
        for (let i in typelist) {
          if (Number(typelist[i].id) == id) {
            let children_list = typelist[i].children_list || [];
            this.setData({
              typesublist: children_list,
            });
            if (children_list.length > 0) {
              this.setData({
                showsubtype: true,
              });
            } else {
              this.setData({
                showsubtype: false,
              });
            }
            break;
          }
        }
      } else {
        this.setData({
          typesublist: [],
          showsubtype: false,
        });
      }
    },
    onShareAppMessage() {
    },
  },
});
